﻿using System.Collections.ObjectModel;
using Microsoft.Extensions.Logging;
using MyToDo.Common;
using MyToDo.Common.Models;
using MyToDo.Extensions;
using MyToDo.Service;
using MyToDo.Shared.Dtos;
using Prism.Commands;
using Prism.Ioc;
using Prism.Regions;
using Prism.Services.Dialogs;

namespace MyToDo.ViewModels
{
    public class IndexViewModel : NavigationViewModel
    {
        private readonly IDialogHostService dialog;
        private readonly ILogger logger;
        private readonly IMemoService memoService;
        private readonly IToDoService toDoService;
        private readonly IRegionManager regionManager;
        private SummaryDto summary;

        private ObservableCollection<TaskBar> taksBars;

        public IndexViewModel(
            IContainerProvider provider,
            IDialogHostService dialog,
            ILogger logger
        )
            : base(provider)
        {
            /// 使用事件订阅,动态通知用户信息改变了
            CreateTaskBars();
            toDoService = provider.Resolve<IToDoService>();
            memoService = provider.Resolve<IMemoService>();
            regionManager = provider.Resolve<IRegionManager>();
            ExcuteCommand = new DelegateCommand<string>(Excute);
            EditToDoCommand = new DelegateCommand<ToDoDto>(AddToDo);
            EditMemoCommand = new DelegateCommand<MemoDto>(AddMemo);
            ToDoCompletedCommand = new DelegateCommand<ToDoDto>(ToDoCompelted);
            NavigateCommand = new DelegateCommand<TaskBar>(Navigate);

            this.dialog = dialog;
            this.logger = logger;
            logger.LogDebug("IndexViewModel init");
        }

        private string title;

        public string Title
        {
            get { return title; }
            set
            {
                title = value;
                RaisePropertyChanged();
            }
        }

        private void Navigate(TaskBar bar)
        {
            if (string.IsNullOrWhiteSpace(bar.Target))
            {
                return;
            }
            NavigationParameters pairs = new NavigationParameters();
            if (bar.Title == "已完成")
            {
                pairs.Add("Value", 2);
            }
            regionManager
                .Regions[PrismManager.MainViewRegionName]
                .RequestNavigate(bar.Target, pairs);
        }

        public DelegateCommand<MemoDto> EditMemoCommand { get; private set; }

        public DelegateCommand<ToDoDto> EditToDoCommand { get; private set; }

        public DelegateCommand<string> ExcuteCommand { get; private set; }

        public DelegateCommand<ToDoDto> ToDoCompletedCommand { get; private set; }

        public DelegateCommand<TaskBar> NavigateCommand { get; private set; }

        public SummaryDto Summary
        {
            get { return summary; }
            set
            {
                summary = value;
                RaisePropertyChanged();
            }
        }

        public ObservableCollection<TaskBar> TaskBars
        {
            get { return taksBars; }
            set
            {
                taksBars = value;
                RaisePropertyChanged();
            }
        }

        public override async void OnNavigatedTo(NavigationContext navigationContext)
        {
            var summaryResult = await toDoService.SummaryAsync();
            if (summaryResult.Status)
            {
                Summary = summaryResult.Result;
                Refresh();
            }
            Title =
                $"你好,{AppSession.UserName}; 今天是{DateTime.Now.GetDateTimeFormats('D')[1].ToString()}。";
            base.OnNavigatedTo(navigationContext);
        }

        /// <summary>
        /// 添加备忘录
        /// </summary>
        /// <param name="model"></param>
        private async void AddMemo(MemoDto model)
        {
            DialogParameters param = new DialogParameters();
            if (model != null)
                param.Add("Value", model);
            var dialogResult = await dialog.ShowDialog("AddMemoView", param);
            if (dialogResult.Result == ButtonResult.OK)
            {
                try
                {
                    UpdateLoading(true);
                    var memo = dialogResult.Parameters.GetValue<MemoDto>("Value");

                    if (memo.Id > 0)
                    {
                        var updateResult = await memoService.UpdateAsync(memo);
                        if (updateResult.Status)
                        {
                            var todoModel = summary.MemoList.FirstOrDefault(t =>
                                t.Id.Equals(memo.Id)
                            );
                            if (todoModel != null)
                            {
                                todoModel.Title = memo.Title;
                                todoModel.Content = memo.Content;
                            }
                        }
                    }
                    else
                    {
                        var addResult = await memoService.AddAsync(memo);
                        if (addResult.Status)
                        {
                            summary.MemoList.Add(addResult.Result);
                        }
                    }
                }
                finally
                {
                    UpdateLoading(false);
                }
            }
        }

        private async void AddToDo(ToDoDto model)
        {
            DialogParameters param = new DialogParameters();
            if (model != null)
            {
                /// 隔离数据
                ///

                param.Add("Value", model);
            }

            var dialogResult = await dialog.ShowDialog("AddToDoView", param);

            if (dialogResult.Result == ButtonResult.OK)
            {
                try
                {
                    UpdateLoading(true);
                    var todo = dialogResult.Parameters.GetValue<ToDoDto>("Value");
                    if (todo.Id > 0)
                    {
                        var updateResult = await toDoService.UpdateAsync(todo);
                        if (updateResult.Status)
                        {
                            var todoModel = summary.ToDoList.FirstOrDefault(t =>
                                t.Id.Equals(todo.Id)
                            );
                            if (todoModel != null)
                            {
                                todoModel.Title = todo.Title;
                                todoModel.Content = todo.Content;
                            }
                        }
                    }
                    else
                    {
                        var addResult = await toDoService.AddAsync(todo);
                        if (addResult.Status)
                        {
                            //更新看板数据
                            summary.Sum = +1;
                            summary.CompletedRatio = (
                                summary.CompletedCount / (double)summary.Sum
                            ).ToString("0%");
                            summary.ToDoList.Add(addResult.Result);
                            this.Refresh();
                        }
                    }
                }
                catch (Exception ex) { }
                finally
                {
                    UpdateLoading(false);
                }
            }
        }

        private void CreateTaskBars()
        {
            TaskBars = new ObservableCollection<TaskBar>();
            TaskBars.Add(
                new TaskBar()
                {
                    Icon = "ClockFast",
                    Title = "汇总",
                    Color = "#FF0CA0FF",
                    Target = "ToDoView",
                }
            );
            TaskBars.Add(
                new TaskBar()
                {
                    Icon = "ClockCheckOutline",
                    Title = "已完成",
                    Color = "#FF1ECA3A",
                    Target = "ToDoView",
                }
            );
            TaskBars.Add(
                new TaskBar()
                {
                    Icon = "ChartLineVariant",
                    Title = "完成率",
                    Color = "#FF02C6DC",
                    Target = "",
                }
            );
            TaskBars.Add(
                new TaskBar()
                {
                    Icon = "PlaylistStar",
                    Title = "备忘录",

                    Color = "#FFFFA000",
                    Target = "MemoView",
                }
            );
        }

        private void Excute(string obj)
        {
            switch (obj)
            {
                case "新增待办":
                    logger.LogInformation("跳转待办");
                    AddToDo(null);
                    break;

                case "新增备忘录":
                    logger.LogInformation("跳转备忘录");
                    AddMemo(null);
                    break;

                default:
                    break;
            }
        }

        /// <summary>
        ///  刷新顶部四个按钮数据数据
        /// </summary>
        /// <exception cref="NotImplementedException"></exception>
        private void Refresh()
        {
            TaskBars[0].Content = summary.Sum.ToString();
            TaskBars[1].Content = summary.CompletedCount.ToString();
            TaskBars[2].Content = summary.CompletedRatio;
            TaskBars[3].Content = summary.MemoeCount.ToString();
            logger.LogInformation("刷新顶部四个按钮数据数据");
        }

        /// <summary>
        ///  设置完成按钮
        /// </summary>
        /// <param name="dto"></param>
        private async void ToDoCompelted(ToDoDto dto)
        {
            try
            {
                UpdateLoading(true);
                var updateResult = await toDoService.UpdateAsync(dto);
                if (updateResult.Status)
                {
                    var todo = Summary.ToDoList.FirstOrDefault(t => t.Id.Equals(dto.Id));
                    if (todo != null)
                    {
                        Summary.ToDoList.Remove(todo);
                        Summary.CompletedCount += 1;
                        Summary.CompletedRatio = (
                            Summary.CompletedCount / (double)Summary.Sum
                        ).ToString("0%");
                        this.Refresh();
                    }
                    aggregator.SendMessage("已完成");
                }
            }
            finally
            {
                UpdateLoading(false);
            }
        }
    }
}
